package com.minxyz.order.service;


import com.minxyz.order.entity.Order;
import com.minxyz.order.repository.OrderRepository;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.transaction.Transactional;

@Service
@AllArgsConstructor
public class OrderService {

    private final OrderRepository orderRepository;

    private final RestTemplate restTemplate;

    @GlobalTransactional
    public void saveSuccess(Order order) throws Exception {
        //此处模拟先调用库存服务扣减库存
        useStock();
        orderRepository.save(order);
    }

    @GlobalTransactional
    public void saveFailure(Order order) throws Exception {
        //此处模拟先调用库存服务扣减库存
        useStock();
        orderRepository.save(order);
        throw new RuntimeException("模拟保存订单失败");
    }

    private void useStock() {
        restTemplate.postForObject("http://localhost:8083/stock", "", String.class);
    }


}
